// AI服务模块 - 增强塔罗牌占卜的智能解读和总结
export class AIService {
  constructor() {
    // 网页版ChatGPT配置
    this.apiConfig = {
      baseUrl: 'https://chat.openai.com/backend-api/conversation',
      apiKey: '', // 网页版不需要API key
      model: 'gpt-3.5-turbo'
    };
    
    // 默认使用本地模式，避免跨域问题
    this.localMode = true;
    this.webMode = false; // 网页版模式
  }

  // 分析用户问题
  async analyzeQuestion(question) {
    if (this.localMode) {
      return this.localQuestionAnalysis(question);
    }
    
    try {
      if (this.webMode) {
        // 使用免费AI服务
        const prompt = `请分析以下问题，提供深入的情感分析和问题洞察：${question}`;
        return await this.callFreeAI(prompt);
      } else {
        // 使用付费OpenAI API
        return await this.callAIAPI('analyze_question', question);
      }
    } catch (error) {
      console.warn('AI服务调用失败，自动切换到本地模式:', error);
      this.localMode = true; // 自动切换到本地模式
      return this.localQuestionAnalysis(question);
    }
  }

  // 生成个性化解读
  async generatePersonalizedInterpretation(question, cards, spread) {
    if (this.localMode) {
      return this.localPersonalizedInterpretation(question, cards, spread);
    }
    
    try {
      if (this.webMode) {
        // 使用免费AI服务
        const prompt = this.buildInterpretationPrompt(question, cards, spread);
        return await this.callFreeAI(prompt);
      } else {
        // 使用付费OpenAI API
        const prompt = this.buildInterpretationPrompt(question, cards, spread);
        return await this.callAIAPI('personalized_interpretation', prompt);
      }
    } catch (error) {
      console.warn('AI服务调用失败，自动切换到本地模式:', error);
      this.localMode = true; // 自动切换到本地模式
      return this.localPersonalizedInterpretation(question, cards, spread);
    }
  }

  // 生成AI总结
  async generateAISummary(question, cards, interpretation, narrative) {
    if (this.localMode) {
      return this.localAISummary(question, cards, interpretation, narrative);
    }
    
    try {
      if (this.webMode) {
        // 使用免费AI服务
        const prompt = this.buildSummaryPrompt(question, cards, interpretation, narrative);
        return await this.callFreeAI(prompt);
      } else {
        // 使用付费OpenAI API
        const prompt = this.buildSummaryPrompt(question, cards, interpretation, narrative);
        return await this.callAIAPI('ai_summary', prompt);
      }
    } catch (error) {
      console.warn('AI服务调用失败，自动切换到本地模式:', error);
      this.localMode = true; // 自动切换到本地模式
      return this.localAISummary(question, cards, interpretation, narrative);
    }
  }

  // 情感分析和建议
  async analyzeEmotionAndAdvice(question, cards) {
    if (this.localMode) {
      return this.localEmotionAnalysis(question, cards);
    }
    
    try {
      if (this.webMode) {
        // 使用免费AI服务
        const prompt = this.buildEmotionPrompt(question, cards);
        return await this.callFreeAI(prompt);
      } else {
        // 使用付费OpenAI API
        const prompt = this.buildEmotionPrompt(question, cards);
        return await this.callAIAPI('emotion_analysis', prompt);
      }
    } catch (error) {
      console.warn('AI服务调用失败，自动切换到本地模式:', error);
      this.localMode = true; // 自动切换到本地模式
      return this.localEmotionAnalysis(question, cards);
    }
  }

  // 本地问题分析（模拟AI）
  localQuestionAnalysis(question) {
    const analysis = {
      emotionalState: this.analyzeEmotionalKeywords(question),
      questionType: this.categorizeQuestion(question),
      urgency: this.assessUrgency(question),
      complexity: this.assessComplexity(question),
      suggestions: this.generateQuestionSuggestions(question)
    };

    return {
      success: true,
      data: analysis,
      message: '本地AI分析完成'
    };
  }

  // 本地个性化解读
  localPersonalizedInterpretation(question, cards, spread) {
    const interpretation = {
      questionInsights: this.extractQuestionInsights(question),
      cardConnections: this.findCardConnections(question, cards),
      personalizedMeanings: this.generatePersonalizedMeanings(question, cards),
      actionGuidance: this.generateActionGuidance(question, cards)
    };

    return {
      success: true,
      data: interpretation,
      message: '本地AI解读生成完成'
    };
  }

  // 本地AI总结
  localAISummary(question, cards, interpretation, narrative) {
    const summary = {
      keyInsights: this.extractKeyInsights(interpretation, narrative),
      emotionalJourney: this.mapEmotionalJourney(cards),
      practicalSteps: this.generatePracticalSteps(cards, interpretation),
      futureOutlook: this.generateFutureOutlook(cards, question),
      wisdomQuotes: this.generateWisdomQuotes(cards)
    };

    return {
      success: true,
      data: summary,
      message: '本地AI总结生成完成'
    };
  }

  // 本地情感分析
  localEmotionAnalysis(question, cards) {
    const analysis = {
      currentEmotions: this.analyzeCurrentEmotions(question, cards),
      emotionalPatterns: this.identifyEmotionalPatterns(cards),
      healingSuggestions: this.generateHealingSuggestions(cards),
      growthOpportunities: this.identifyGrowthOpportunities(cards)
    };

    return {
      success: true,
      data: analysis,
      message: '本地AI情感分析完成'
    };
  }

  // 分析情感关键词
  analyzeEmotionalKeywords(question) {
    const emotions = {
      fear: ['担心', '害怕', '恐惧', '焦虑', '不安'],
      hope: ['希望', '期待', '梦想', '愿望', '憧憬'],
      confusion: ['困惑', '迷茫', '不确定', '犹豫', '纠结'],
      anger: ['愤怒', '生气', '不满', '烦躁', '恼火'],
      sadness: ['悲伤', '难过', '失落', '沮丧', '痛苦'],
      joy: ['快乐', '开心', '兴奋', '满足', '幸福'],
      love: ['爱', '喜欢', '关心', '温暖', '亲密']
    };

    const foundEmotions = {};
    Object.entries(emotions).forEach(([emotion, keywords]) => {
      const count = keywords.filter(keyword => question.includes(keyword)).length;
      if (count > 0) {
        foundEmotions[emotion] = count;
      }
    });

    return foundEmotions;
  }

  // 问题分类
  categorizeQuestion(question) {
    if (question.includes('关系') || question.includes('感情') || question.includes('爱情')) {
      return 'relationship';
    } else if (question.includes('工作') || question.includes('事业') || question.includes('职业')) {
      return 'career';
    } else if (question.includes('健康') || question.includes('身体') || question.includes('疾病')) {
      return 'health';
    } else if (question.includes('金钱') || question.includes('财富') || question.includes('投资')) {
      return 'finance';
    } else if (question.includes('学习') || question.includes('考试') || question.includes('教育')) {
      return 'education';
    } else {
      return 'general';
    }
  }

  // 评估问题紧急程度
  assessUrgency(question) {
    const urgentKeywords = ['现在', '马上', '立即', '紧急', '危机', '危险'];
    const urgentCount = urgentKeywords.filter(keyword => question.includes(keyword)).length;
    
    if (urgentCount >= 2) return 'high';
    if (urgentCount >= 1) return 'medium';
    return 'low';
  }

  // 评估问题复杂度
  assessComplexity(question) {
    const length = question.length;
    const hasMultipleAspects = question.includes('和') || question.includes('以及') || question.includes('同时');
    
    if (length > 100 || hasMultipleAspects) return 'complex';
    if (length > 50) return 'moderate';
    return 'simple';
  }

  // 生成问题建议
  generateQuestionSuggestions(question) {
    const suggestions = [];
    
    if (question.length < 20) {
      suggestions.push('尝试更详细地描述你的情况，包括具体的情境和感受');
    }
    
    if (!question.includes('？') && !question.includes('?')) {
      suggestions.push('将你的描述转化为具体的问题，这样能获得更精准的指引');
    }
    
    if (question.includes('永远') || question.includes('绝对')) {
      suggestions.push('避免使用绝对化的词汇，保持开放和灵活的心态');
    }
    
    return suggestions;
  }

  // 提取问题洞察
  extractQuestionInsights(question) {
    const insights = [];
    
    // 分析问题的时间维度
    if (question.includes('过去')) insights.push('你正在回顾过去的经历，寻找答案');
    if (question.includes('现在')) insights.push('你关注当下的状况，寻求指引');
    if (question.includes('未来')) insights.push('你展望未来，希望了解可能的发展');
    
    // 分析问题的情感维度
    const emotions = this.analyzeEmotionalKeywords(question);
    if (Object.keys(emotions).length > 0) {
      insights.push(`你的问题带有${Object.keys(emotions).join('、')}等情感色彩`);
    }
    
    return insights;
  }

  // 寻找牌与问题的连接
  findCardConnections(question, cards) {
    const connections = [];
    
    cards.forEach(card => {
      const keywords = card.keywords.join('、');
      const questionKeywords = this.extractKeywords(question);
      
      // 寻找关键词匹配
      const matches = questionKeywords.filter(keyword => 
        keywords.includes(keyword) || card.name.includes(keyword)
      );
      
      if (matches.length > 0) {
        connections.push({
          card: card.name,
          connection: `关键词"${matches.join('、')}"将你的问题与${card.name}连接起来`,
          significance: '这张牌对你的问题有特殊的指导意义'
        });
      }
    });
    
    return connections;
  }

  // 提取关键词
  extractKeywords(text) {
    const stopWords = ['的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'];
    const words = text.split(/[，。！？\s]+/).filter(word => 
      word.length > 1 && !stopWords.includes(word)
    );
    return words.slice(0, 10); // 返回前10个关键词
  }

  // 生成个性化含义
  generatePersonalizedMeanings(question, cards) {
    return cards.map(card => {
      const isReversed = card.isReversed;
      const baseMeaning = isReversed ? card.reversed.meaning : card.upright.meaning;
      
      return {
        card: card.name,
        personalMeaning: `结合你的问题"${question.substring(0, 30)}..."，${card.name}告诉你${baseMeaning}`,
        relevance: this.assessCardRelevance(card, question),
        personalAdvice: this.generatePersonalAdvice(card, question)
      };
    });
  }

  // 评估牌与问题的相关性
  assessCardRelevance(card, question) {
    const questionKeywords = this.extractKeywords(question);
    const cardKeywords = card.keywords;
    
    const matches = questionKeywords.filter(keyword => 
      cardKeywords.some(cardKeyword => cardKeyword.includes(keyword))
    );
    
    if (matches.length >= 2) return 'high';
    if (matches.length >= 1) return 'medium';
    return 'low';
  }

  // 生成个人建议
  generatePersonalAdvice(card, question) {
    const questionType = this.categorizeQuestion(question);
    const isReversed = card.isReversed;
    
    const adviceMap = {
      relationship: {
        upright: `在关系方面，${card.name}建议你保持开放和真诚`,
        reversed: `在关系方面，${card.name}提醒你需要重新审视和调整`
      },
      career: {
        upright: `在事业方面，${card.name}鼓励你积极行动和追求目标`,
        reversed: `在事业方面，${card.name}建议你重新评估方向和策略`
      },
      general: {
        upright: `${card.name}为你带来积极的指引，相信自己的直觉`,
        reversed: `${card.name}提醒你注意潜在的问题，寻找新的解决方案`
      }
    };
    
    const advice = adviceMap[questionType] || adviceMap.general;
    return isReversed ? advice.reversed : advice.upright;
  }

  // 生成行动指导
  generateActionGuidance(question, cards) {
    const guidance = {
      immediate: this.generateImmediateActions(cards),
      shortTerm: this.generateShortTermActions(cards),
      longTerm: this.generateLongTermActions(cards),
      mindset: this.generateMindsetGuidance(cards)
    };
    
    return guidance;
  }

  // 生成立即行动
  generateImmediateActions(cards) {
    const actions = [];
    
    cards.forEach(card => {
      if (card.isReversed) {
        actions.push(`重新审视${card.name}所代表的方面`);
      } else {
        actions.push(`发挥${card.name}的积极能量`);
      }
    });
    
    return actions.slice(0, 3); // 返回前3个行动
  }

  // 生成短期行动
  generateShortTermActions(cards) {
    return [
      '制定具体的行动计划',
      '寻求相关的建议和支持',
      '保持开放和灵活的心态'
    ];
  }

  // 生成长期行动
  generateLongTermActions(cards) {
    return [
      '建立持续的个人成长习惯',
      '培养相关的技能和能力',
      '保持对未来的希望和信心'
    ];
  }

  // 生成心态指导
  generateMindsetGuidance(cards) {
    const reversedCount = cards.filter(card => card.isReversed).length;
    
    if (reversedCount > cards.length / 2) {
      return '当前需要更多反思和调整，保持耐心和信心';
    } else if (reversedCount < cards.length / 3) {
      return '能量积极，保持乐观和行动力';
    } else {
      return '保持平衡，既有行动也有反思';
    }
  }

  // 提取关键洞察
  extractKeyInsights(interpretation, narrative) {
    const insights = [];
    
    // 从解读中提取关键信息
    if (interpretation.includes('正位')) {
      insights.push('牌组整体能量积极向上');
    }
    if (interpretation.includes('逆位')) {
      insights.push('需要重新审视和调整某些方面');
    }
    
    // 从叙事中提取主题
    if (narrative.includes('整体主题')) {
      const themeMatch = narrative.match(/整体主题：(.+)/);
      if (themeMatch) {
        insights.push(`核心主题：${themeMatch[1]}`);
      }
    }
    
    return insights;
  }

  // 映射情感旅程
  mapEmotionalJourney(cards) {
    const journey = cards.map((card, index) => {
      const position = `位置${index + 1}`;
      const emotion = this.mapCardToEmotion(card);
      
      return {
        position,
        card: card.name,
        emotion,
        message: `${position}：${emotion} - ${card.name}带来${emotion}的体验`
      };
    });
    
    return journey;
  }

  // 将牌映射到情感
  mapCardToEmotion(card) {
    const emotionMap = {
      '愚者': '纯真和冒险',
      '魔术师': '创造力和自信',
      '女祭司': '直觉和智慧',
      '女皇': '丰盛和滋养',
      '皇帝': '权威和稳定',
      '教皇': '信仰和传统',
      '恋人': '选择和和谐',
      '战车': '意志和胜利',
      '力量': '勇气和耐心',
      '隐者': '内省和指导'
    };
    
    return emotionMap[card.name] || '神秘和未知';
  }

  // 生成实用步骤
  generatePracticalSteps(cards, interpretation) {
    const steps = [];
    
    cards.forEach((card, index) => {
      const step = {
        step: index + 1,
        action: this.generateCardAction(card),
        timeframe: this.suggestTimeframe(card),
        priority: this.assessPriority(card)
      };
      steps.push(step);
    });
    
    return steps;
  }

  // 生成牌的行动
  generateCardAction(card) {
    if (card.isReversed) {
      return `重新审视${card.name}所代表的方面，寻找新的方法`;
    } else {
      return `发挥${card.name}的能量，积极行动`;
    }
  }

  // 建议时间框架
  suggestTimeframe(card) {
    const timeframes = ['立即', '今天', '本周', '本月', '本季度'];
    const randomIndex = Math.floor(Math.random() * timeframes.length);
    return timeframes[randomIndex];
  }

  // 评估优先级
  assessPriority(card) {
    if (card.isReversed) return 'high';
    if (card.keywords.includes('机会') || card.keywords.includes('新开始')) return 'high';
    return 'medium';
  }

  // 生成未来展望
  generateFutureOutlook(cards, question) {
    const positiveCards = cards.filter(card => !card.isReversed).length;
    const totalCards = cards.length;
    
    if (positiveCards > totalCards * 0.7) {
      return '未来充满希望和可能性，保持积极行动';
    } else if (positiveCards < totalCards * 0.3) {
      return '当前面临挑战，但每一次挑战都是成长的机会';
    } else {
      return '未来充满变化和机遇，保持开放和灵活的心态';
    }
  }

  // 生成智慧语录
  generateWisdomQuotes(cards) {
    const quotes = [
      '塔罗牌是镜子，反映的是你内心的智慧和直觉',
      '每一次抽牌都是与内心对话的机会',
      '相信自己的判断，勇敢地面对挑战和机遇',
      '塔罗牌的指引来自你内心的声音',
      '保持开放的心态，接受所有的可能性'
    ];
    
    // 根据牌组选择相关的语录
    const selectedQuotes = [];
    cards.forEach((card, index) => {
      const quoteIndex = index % quotes.length;
      selectedQuotes.push({
        card: card.name,
        quote: quotes[quoteIndex]
      });
    });
    
    return selectedQuotes;
  }

  // 分析当前情感
  analyzeCurrentEmotions(question, cards) {
    const emotions = this.analyzeEmotionalKeywords(question);
    const cardEmotions = this.analyzeCardEmotions(cards);
    
    return {
      questionEmotions: emotions,
      cardEmotions: cardEmotions,
      overallMood: this.assessOverallMood(emotions, cardEmotions)
    };
  }

  // 分析牌的情感
  analyzeCardEmotions(cards) {
    const emotions = {};
    
    cards.forEach(card => {
      if (card.isReversed) {
        emotions.uncertainty = (emotions.uncertainty || 0) + 1;
      } else {
        emotions.confidence = (emotions.confidence || 0) + 1;
      }
    });
    
    return emotions;
  }

  // 评估整体情绪
  assessOverallMood(questionEmotions, cardEmotions) {
    const positiveEmotions = ['hope', 'joy', 'love', 'confidence'];
    const negativeEmotions = ['fear', 'confusion', 'anger', 'sadness', 'uncertainty'];
    
    let positiveScore = 0;
    let negativeScore = 0;
    
    Object.entries(questionEmotions).forEach(([emotion, count]) => {
      if (positiveEmotions.includes(emotion)) {
        positiveScore += count;
      } else if (negativeEmotions.includes(emotion)) {
        negativeScore += count;
      }
    });
    
    if (cardEmotions.confidence) positiveScore += cardEmotions.confidence;
    if (cardEmotions.uncertainty) negativeScore += cardEmotions.uncertainty;
    
    if (positiveScore > negativeScore) return 'positive';
    if (negativeScore > positiveScore) return 'negative';
    return 'balanced';
  }

  // 识别情感模式
  identifyEmotionalPatterns(cards) {
    const patterns = [];
    
    // 分析正逆位模式
    const reversedCount = cards.filter(card => card.isReversed).length;
    if (reversedCount > cards.length / 2) {
      patterns.push('当前面临较多挑战，需要重新审视和调整');
    } else if (reversedCount < cards.length / 3) {
      patterns.push('整体能量积极，适合采取行动');
    } else {
      patterns.push('平衡状态，需要整合不同方面的能量');
    }
    
    // 分析元素模式
    const elementCounts = {};
    cards.forEach(card => {
      if (card.element) {
        elementCounts[card.element] = (elementCounts[card.element] || 0) + 1;
      }
    });
    
    const dominantElement = Object.entries(elementCounts)
      .sort(([,a], [,b]) => b - a)[0];
    
    if (dominantElement) {
      patterns.push(`${dominantElement[0]}元素占主导，强调${this.getElementTheme(dominantElement[0])}`);
    }
    
    return patterns;
  }

  // 获取元素主题
  getElementTheme(element) {
    const themes = {
      '火': '行动与激情',
      '水': '情感与直觉',
      '风': '思维与沟通',
      '土': '物质与稳定'
    };
    return themes[element] || '个人成长';
  }

  // 生成治愈建议
  generateHealingSuggestions(cards) {
    const suggestions = [];
    
    cards.forEach(card => {
      if (card.isReversed) {
        suggestions.push(`通过${card.name}的逆位，学会接纳和转化挑战`);
      } else {
        suggestions.push(`保持${card.name}的正位能量，继续前进`);
      }
    });
    
    return suggestions;
  }

  // 识别成长机会
  identifyGrowthOpportunities(cards) {
    const opportunities = [];
    
    cards.forEach(card => {
      if (card.isReversed) {
        opportunities.push(`${card.name}的逆位提醒你注意需要改进的方面`);
      } else {
        opportunities.push(`${card.name}的正位为你带来新的可能性`);
      }
    });
    
    return opportunities;
  }

  // 构建解读提示词
  buildInterpretationPrompt(question, cards, spread) {
    return `请基于以下信息生成个性化的塔罗牌解读：

问题：${question}
阵型：${spread.name}
抽到的牌：${cards.map(card => `${card.name}(${card.isReversed ? '逆位' : '正位'})`).join('、')}

请提供：
1. 问题深层分析
2. 每张牌与问题的关联
3. 个性化含义解读
4. 具体行动建议`;
  }

  // 构建总结提示词
  buildSummaryPrompt(question, cards, interpretation, narrative) {
    return `请总结以下塔罗牌占卜结果：

问题：${question}
牌组：${cards.map(card => card.name).join('、')}
基础解读：${interpretation.substring(0, 500)}...
叙事重构：${narrative.substring(0, 500)}...

请提供：
1. 关键洞察总结
2. 情感旅程分析
3. 实用行动步骤
4. 未来展望
5. 智慧语录`;
  }

  // 构建情感分析提示词
  buildEmotionPrompt(question, cards) {
    return `请分析以下塔罗牌占卜的情感层面：

问题：${question}
牌组：${cards.map(card => `${card.name}(${card.isReversed ? '逆位' : '正位'})`).join('、')}

请提供：
1. 当前情感状态分析
2. 情感模式识别
3. 治愈建议
4. 成长机会`;
  }

  // 调用免费AI服务
  async callFreeAI(prompt) {
    const freeAIServices = [
      'https://api.freegpt4.tech/v1/chat/completions',
      'https://api.deepseek.com/v1/chat/completions',
      'https://api.anthropic.com/v1/messages'
    ];

    for (let i = 0; i < freeAIServices.length; i++) {
      try {
        console.log(`尝试调用免费AI服务 ${i + 1}...`);
        
        const response = await fetch(freeAIServices[i], {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: 'gpt-3.5-turbo',
            messages: [
              {
                role: 'user',
                content: prompt
              }
            ],
            max_tokens: 1000,
            temperature: 0.7
          })
        });

        if (response.ok) {
          const data = await response.json();
          
          if (data.choices && data.choices[0] && data.choices[0].message) {
            const aiResponse = data.choices[0].message.content;
            console.log(`免费AI服务 ${i + 1} 调用成功`);
            return {
              success: true,
              data: {
                message: aiResponse,
                rawResponse: aiResponse
              },
              message: 'AI分析完成'
            };
          }
        }
      } catch (error) {
        console.warn(`免费AI服务 ${i + 1} 调用失败:`, error);
        continue; // 尝试下一个服务
      }
    }
    
    // 所有免费服务都失败，抛出错误
    throw new Error('所有免费AI服务都无法访问，请稍后再试');
  }

  // 调用OpenAI API (保留原方法)
  async callAIAPI(endpoint, prompt) {
    const maxRetries = 3;
    const baseDelay = 1000; // 基础延迟1秒
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        console.log(`尝试调用OpenAI API (第${attempt}次)...`);
        
        const response = await fetch(this.apiConfig.baseUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.apiConfig.apiKey}`
          },
          body: JSON.stringify({
            model: this.apiConfig.model,
            messages: [
              {
                role: 'system',
                content: this.getSystemPrompt(endpoint)
              },
              {
                role: 'user',
                content: prompt
              }
            ],
            max_tokens: 1500, // 减少token使用
            temperature: 0.7
          })
        });

        if (response.ok) {
          const data = await response.json();
          
          if (data.choices && data.choices[0] && data.choices[0].message) {
            const aiResponse = data.choices[0].message.content;
            console.log('OpenAI API调用成功');
            return this.parseAIResponse(endpoint, aiResponse);
          } else {
            throw new Error('API响应格式错误');
          }
        } else if (response.status === 429) {
          // 速率限制，等待更长时间
          const retryAfter = response.headers.get('Retry-After');
          const waitTime = retryAfter ? parseInt(retryAfter) * 1000 : baseDelay * Math.pow(2, attempt);
          
          console.log(`遇到速率限制，等待${waitTime/1000}秒后重试...`);
          await this.sleep(waitTime);
          
          if (attempt === maxRetries) {
            throw new Error(`API速率限制，请稍后再试。建议等待${Math.ceil(waitTime/1000)}秒。`);
          }
        } else if (response.status === 401) {
          throw new Error('API密钥无效，请检查配置');
        } else if (response.status === 403) {
          throw new Error('API访问被拒绝，请检查账户状态');
        } else if (response.status >= 500) {
          // 服务器错误，等待后重试
          const waitTime = baseDelay * Math.pow(2, attempt);
          console.log(`服务器错误，等待${waitTime/1000}秒后重试...`);
          await this.sleep(waitTime);
          
          if (attempt === maxRetries) {
            throw new Error('OpenAI服务器暂时不可用，请稍后再试');
          }
        } else {
          throw new Error(`API调用失败: ${response.status} ${response.statusText}`);
        }
      } catch (error) {
        console.error(`OpenAI API调用失败 (第${attempt}次):`, error);
        
        if (attempt === maxRetries) {
          // 最后一次尝试失败，抛出错误
          throw error;
        } else {
          // 等待后重试
          const waitTime = baseDelay * Math.pow(2, attempt);
          console.log(`等待${waitTime/1000}秒后重试...`);
          await this.sleep(waitTime);
        }
      }
    }
  }

  // 延迟函数
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  // 获取系统提示词
  getSystemPrompt(endpoint) {
    const prompts = {
      'analyze_question': '你是一个专业的塔罗牌占卜师和心理咨询师。请分析用户的问题，提供深入的情感分析和问题洞察。',
      'personalized_interpretation': '你是一个专业的塔罗牌解读师。请基于用户的问题和抽到的牌，提供个性化的解读和建议。',
      'ai_summary': '你是一个专业的塔罗牌总结师。请总结占卜结果，提取关键洞察，并提供实用的行动建议。',
      'emotion_analysis': '你是一个专业的情感分析师。请分析用户的情感状态，识别模式，并提供治愈和成长建议。'
    };
    
    return prompts[endpoint] || '你是一个专业的塔罗牌占卜助手，请为用户提供准确、有意义的分析和建议。';
  }

  // 解析AI响应
  parseAIResponse(endpoint, aiResponse) {
    try {
      // 尝试解析JSON格式的响应
      if (aiResponse.includes('{') && aiResponse.includes('}')) {
        const jsonMatch = aiResponse.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          return JSON.parse(jsonMatch[0]);
        }
      }
      
      // 如果不是JSON，返回格式化的响应
      return {
        success: true,
        data: {
          message: aiResponse,
          rawResponse: aiResponse
        },
        message: 'AI分析完成'
      };
    } catch (error) {
      console.warn('AI响应解析失败，返回原始响应:', error);
      return {
        success: true,
        data: {
          message: aiResponse,
          rawResponse: aiResponse
        },
        message: 'AI分析完成'
      };
    }
  }

  // 设置API配置
  setAPIConfig(config) {
    this.apiConfig = { ...this.apiConfig, ...config };
    this.localMode = !config.apiKey;
  }

  // 切换模式
  toggleMode() {
    if (this.localMode) {
      this.localMode = false;
      this.webMode = true;
      return '免费AI模式';
    } else if (this.webMode) {
      this.webMode = false;
      this.localMode = true;
      return '本地模式';
    }
  }

  // 设置免费AI模式
  setFreeAIMode() {
    this.localMode = false;
    this.webMode = true;
    console.log('已切换到免费AI模式');
    return '免费AI模式';
  }

  // 设置本地模式
  setLocalMode() {
    this.localMode = true;
    this.webMode = false;
    console.log('已切换到本地模式');
    return '本地模式';
  }

  // 获取API状态
  getAPIStatus() {
    let status = '本地模式';
    if (this.webMode) {
      status = '免费AI模式';
    } else if (!this.localMode) {
      status = '付费OpenAI模式';
    }
    
    return {
      localMode: this.localMode,
      webMode: this.webMode,
      apiKey: this.apiConfig.apiKey ? '已配置' : '未配置',
      baseUrl: this.apiConfig.baseUrl,
      model: this.apiConfig.model,
      status: status
    };
  }

  // 测试API连接
  async testAPIConnection() {
    if (this.localMode) {
      return { success: false, message: '当前为本地模式，无法测试API连接' };
    }

    try {
      const response = await fetch(this.apiConfig.baseUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiConfig.apiKey}`
        },
        body: JSON.stringify({
          model: this.apiConfig.model,
          messages: [{ role: 'user', content: 'test' }],
          max_tokens: 5
        })
      });

      if (response.ok) {
        return { success: true, message: 'API连接正常' };
      } else {
        return { 
          success: false, 
          message: `API连接失败: ${response.status} ${response.statusText}`,
          status: response.status
        };
      }
    } catch (error) {
      return { 
        success: false, 
        message: `API连接错误: ${error.message}`,
        error: error
      };
    }
  }

  // 重置为OpenAI模式
  resetToOpenAIMode() {
    this.localMode = false;
    console.log('已重置为OpenAI模式');
    return 'OpenAI模式';
  }
}

// 创建默认实例
export const aiService = new AIService(); 